package com.ziq.base.service

import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.os.IBinder

class LongLinkServiceWarp {

    var context: Context? = null
    var serviceBinder: ILongLinkService? = null

    constructor(context: Context){
        this.context = context
    }

    var onServiceConnected : (()->Unit)? =null
    var onServiceDisconnected : (()->Unit)? =null

    private var serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            serviceBinder = ILongLinkService.Stub.asInterface(service)
            onServiceConnected?.invoke()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            serviceBinder = null
            onServiceDisconnected?.invoke()
        }
    }

    fun init(onServiceConnected : (()->Unit)?= null, onServiceDisconnected : (()->Unit)? =null) {
        this.onServiceConnected = onServiceConnected
        this.onServiceDisconnected = onServiceDisconnected
        LongLinkService.startZQPlayerService(context!!)
        LongLinkService.bindZQPlayerService(context!!, serviceConnection)
    }

    fun destroy(): Unit {
        LongLinkService.unbindZQPlayerService(context!!, serviceConnection)
    }

    fun connect(info : ConnectInfo) {
        serviceBinder?.connect(info)
    }

    fun disconnect() {
        serviceBinder?.disconnect()
    }

    fun send(message : ByteArray) {
        serviceBinder?.send(message)
    }

    fun registerListener(listener : ILongLinkListener) {
        serviceBinder?.registerListener(listener)
    }

    fun unregisterListener(listener : ILongLinkListener) {
        serviceBinder?.unregisterListener(listener)
    }
}